import axios from "axios"; // 引用axios
import config from "./config.js";
import Encryption from '../util/encryption.js'
import { ElLoading,ElMessage,ElMessageBox } from 'element-plus'
/**请求失败后的错误统一处理 */

// key for des
const desKey = config.key();
var time = new Date().getMilliseconds();
var oldTime =localStorage.getItem("time");
if(oldTime){
	time = oldTime;
}

const instance = axios.create({
  baseURL: config.baseUrl.api,
  timeout: 60000,
  withCredentials:true,
  headers: { 
	"x-requested-with": "XMLHttpRequest"
  ,"From-Time":"true"
  ,"Content-Type":"application/json;charset=UTF-8"
  ,"Timestamp":time
  }
});


function redirectLoginPage(message){
	      ElMessageBox.alert(message, '会话失效', {
	        confirmButtonText: 'OK',
	        callback: (action) => {
				let theme =	localStorage.getItem("theme");
				window.parent.location = theme==null || theme == 'yxy'?'/#/login':'/' + theme + '/#/login'
	        },
	      })
		  for (let i = 1; i < 100; i++) {
		    clearInterval(i);
		  }
}
function redirectToLoginPage(data){
	let theme =	localStorage.getItem("theme");
	localStorage.setItem("data.reason",data.reason?data.reason:null)
	window.parent.location = theme==null || theme == 'yxy'?'/#/login':'/' + theme + '/#/login'
}

function TransferString(content)  
{  
    var string = content;  
    try{  
        string=string.replace(/\r\n/g,"")  
        string=string.replace(/\n/g,"");  
    }catch(e) {  
      console.error(e)
    }  
    return string;  
} 
var redirectTimer = null;
instance.interceptors.response.use(
 // 请求成功
    res => {
			
			if(res.data.success === true){
				if(res.data.data != null && res.data.data.length > 0){
					let decryptData = Encryption.DESDecrypt(TransferString(res.data.data),desKey);
					res.data = JSON.parse(decryptData);
				}
				if(redirectTimer != null){
					clearTimeout(redirectTimer);
				}
				//console.log(res.data)
				return Promise.resolve(res);
			}else if(res.data.message == 'redirect'){
				//redirectLoginPage('账号在别处登录或者会话已过期...');
				if(redirectTimer == null){
					redirectTimer = setTimeout(function(){
							redirectToLoginPage(res.data)
					},60*1000)
				}
			}else if(res.data.code == '0000'){
				//redirectLoginPage('账号在别处登录或者会话已过期...');
				return Promise.resolve(res);
			}else{
				ElMessage({
							showClose: true,
							message: res.data.message,
							type: 'error',
						  })
				return Promise.reject(res);
			}
	},
    // 请求失败
    error => {
        const { response } = error;
        if (response) {
           // 状态码判断
           switch (response.status) {
				// 401: 未登录状态，跳转登录页
				case 401:
				//redirectLoginPage();
           		break;
               // 403 token过期
               // 清除token并跳转登录页
               case 403: 
                   break;
               // 404请求不存在
               case 404:
                   break;   
			   // 302请求不存在
			   case 302:
			/* 	if(response.headers['location'].indexOf('/cbgzs/web') >= 0){
					redirectLoginPage();
				} */
			    console.log(302);
				   break;
               default:
                   console.log("other");
               }
            return Promise.reject(response.data);
        } else {
			//redirectLoginPage();
            // 处理断网的情况
            // eg:请求超时或断网时，更新state的network状态
            // network状态在app.vue中控制着一个全局的断网提示组件的显示隐藏
            // 关于断网组件中的刷新重新获取数据，会在断网组件中说明
            // store.commit('changeNetwork', false);
		 	ElMessage({
						showClose: true,
						message: 'Oops, 请检查网络.',
						type: 'error',
					  }) 
        }
    });
// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 动态获取 token（如从 localStorage 或 Vuex/Redux 中获取）
    const token = localStorage.getItem('token');
    if (token) {
      // 动态添加 Authorization 头
      config.headers['token'] = token;
	  config.headers['Cer-Sign'] = token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
//get请求
function get(url, params = {}) {
  return new Promise((resolve, reject) => {
    instance
      .get(url, {
        params: params,
      })
      .then((response) => {
        resolve(response);
      })
      .catch((err) => {
        reject(err);
      });
  });
}
//post请求
function post(url, data = {}) {
  return new Promise((resolve, reject) => {
	  
	let jsonData = JSON.stringify(data);
	//console.log(jsonData)
	let encrypptData = Encryption.DESEncrypt(jsonData,desKey);
	
    instance.post(url, {param:encrypptData}).then(
      (response) => {
        resolve(response!=undefined?response.data:{});
      },
      (err) => {
        reject(err);
      }
    );
  });
}

//post请求
function postWithOutEnc(url, data = {}) {
  return new Promise((resolve, reject) => {
	//let jsonData = JSON.stringify(data);
	//console.log(jsonData)
	//let encrypptData = Encryption.DESEncrypt(jsonData,desKey);
    instance.post(url, data).then(
      (response) => {
        resolve(response!=undefined?response.data:{});
      },
      (err) => {
        reject(err);
      }
    );
  });
}

const qs = require('qs');
//post请求
function postForm(url, data = {}) {
  return new Promise((resolve, reject) => {
	  let jsonData = JSON.stringify(data);
	 // console.log(jsonData)
	let encrypptData = Encryption.DESEncrypt(jsonData,desKey);
    instance.post(url, qs.stringify({param:encrypptData})).then(
      (response) => {
        resolve(response!=undefined?response.data:{});
      },
      (err) => {
        reject(err);
      }
    );
  });
}

//post请求
function postFormWitoutEnc(url, data = {}) {
  return new Promise((resolve, reject) => {
    instance.post(url, qs.stringify(data)).then(
      (response) => {
        resolve(response!=undefined?response.data:{});
      },
      (err) => {
        reject(err);
      }
    );
  });
}

   
export default{
	login(form){
		//return post("/login/checkUserWeb?ptgPw="+form.ptgPw,form)
		return post("/from/checkInfo",form)
	},
	checkDataBaseNormal(form){
		return post("/from/checkDataBaseNormal",form)
	},
	recordDataBaseErrorReason(form){
		return post("/from/recordDataBaseErrorReason",form)
	}
}